package org.xxpay.pay.channel.ysepay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.StrUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayNotify;
import org.xxpay.pay.channel.ysepay.util.SignUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class YsepayPayNotifyService extends BasePayNotify {

    @Autowired
    private YsepayDivisionService ysepayDivisionService;

    private static final MyLog logger = MyLog.getLog(YsepayPayNotifyService.class);

    @Override
    public String getChannelName() {
        return YsepayConfig.CHANNEL_NAME_YSEPAY;
    }

    @Override
    public JSONObject doNotify(Object notifyData) {

        // 构建返回对象
        JSONObject retObj = buildRetObj();
        try {
            String logPrefix = "【处理银盛支付回调】";
            logger.info("====== 开始处理银盛支付回调通知 ======");
            HttpServletRequest request = (HttpServletRequest) notifyData;
            Map<String, String> resParams = buildNotifyData(request);  //将参数转换为map格式

            if(resParams == null || resParams.isEmpty()) {
                throw new Exception("reqParams is null or empty");
            }

            String payOrderId = resParams.get("out_trade_no");
            PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
            if(payOrder == null){
                throw new Exception("订单查询失败！");
            }

            YsepayConfig ysepayConfig = new YsepayConfig(getPayParam(payOrder));  //获取银盛配置信息
            String publicCerFilePath = payConfig.getCertRootPath() + File.separator + getChannelName() + File.separator + ysepayConfig.getPublicCerPath();

            //验签
            boolean isTrue = SignUtils.rsaCheckContent(publicCerFilePath, resParams, resParams.get("sign"));
            if(!isTrue){  //验签失败
                throw new Exception("验签失败！");
            }

            logger.info("{}验证支付通知数据及签名通过", logPrefix);
            String tradeStatus = resParams.get("trade_status");		// 交易状态
            // 支付状态成功或者完成
            if (PayConstant.AlipayConstant.TRADE_STATUS_SUCCESS.equals(tradeStatus) ||
                    PayConstant.AlipayConstant.TRADE_STATUS_FINISHED.equals(tradeStatus) ) {

                int updatePayOrderRows;
                byte payStatus = payOrder.getStatus(); // 0：订单生成，1：支付中，-1：支付失败，2：支付成功，3：业务处理完成，-2：订单过期
                if (payStatus != PayConstant.PAY_STATUS_SUCCESS && payStatus != PayConstant.PAY_STATUS_COMPLETE) {
                    updatePayOrderRows = commonService.payOrderService.updateStatus4Success(payOrder.getPayOrderId(), StrUtil.toString(resParams.get("trade_no"), null));

                    //更新失败 返回fail
                    if (updatePayOrderRows != 1) {
                        logger.error("{}更新支付状态失败,将payOrderId={},更新payStatus={}失败", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
                        logger.info("{}响应给银盛结果：{}", logPrefix, PayConstant.RETURN_ALIPAY_VALUE_FAIL);
                        retObj.put("resResult", PayConstant.RETURN_ALIPAY_VALUE_FAIL);
                        return retObj;
                    }
                    logger.info("{}更新支付状态成功,将payOrderId={},更新payStatus={}成功", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);

                    payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);
                }
            }else{
                // 其他状态
                logger.info("{}支付状态trade_status={},不做业务处理", logPrefix, tradeStatus);
                logger.info("{}响应给银盛结果：{}", logPrefix, PayConstant.RETURN_ALIPAY_VALUE_SUCCESS);
                retObj.put(PayConstant.RESPONSE_RESULT, PayConstant.RETURN_ALIPAY_VALUE_SUCCESS);
                return retObj;
            }

            //更新成功
            baseNotify4MchPay.doNotify(payOrder, true);
            logger.info("====== 完成处理银盛支付回调通知 ======");
            retObj.put(PayConstant.RESPONSE_RESULT, PayConstant.RETURN_ALIPAY_VALUE_SUCCESS);
            return retObj;

        } catch (Exception e) {
           logger.error("ysepay notify error: ", e);
            retObj.put(PayConstant.RESPONSE_RESULT, PayConstant.RETURN_ALIPAY_VALUE_FAIL);
            return retObj;
        }
    }

    //将请求参数转换为 map格式
    public Map buildNotifyData(HttpServletRequest request) {
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }

}
